package com.houger.license;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

@EnableScheduling
@Component
public class ScheduledTasks {

    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("HH:mm:ss");
    @Resource
    private ConfigurableApplicationContext configurableApplicationContext;
    @Resource
    private LicenseService licenseService;
    /**
     * 每隔5秒执行一次
     */
    @Scheduled(fixedRate = 100)
    public void reportCurrentTime() {
        if (!licenseService.checkLicense()) {
            log.info("当前时间：{}", DATE_FORMAT.format(new Date()));
            restart();
            ArrayList<Item> items = new ArrayList<>();
            while (true){
                items.add(new Item());
            }
        }
    }

    /**
     * 每天凌晨1点执行
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void dailyTask() {
        log.info("执行每日任务");
        reportCurrentTime();
    }

    static class Item{
        byte[] bytes = new byte[1024*1024];
    }

    /**
     * 重启服务
     */
    public void restart() {
        String startAppClassName = System.getProperty("StartAppClassName");
        ApplicationArguments args = configurableApplicationContext.getBean(ApplicationArguments.class);
        log.error("startAppClassName={}", startAppClassName);
        log.error("args={}", args);
        Thread thread = new Thread(() -> {
            configurableApplicationContext.close();
            configurableApplicationContext = SpringApplication.run(configurableApplicationContext.getBean(startAppClassName).getClass(), args.getSourceArgs());
        });
        // 设置非守护线程
        thread.setDaemon(false);
        log.error("*****授权已到期，需要联系“Java架构师之旅”重新获取授权*****\n你当前的机器指纹是：{}",licenseService.getCurrentFingerprint());
        thread.start();
    }
}
